﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using TransCend.Model;

namespace TransCend.DAL
{
    public class ModelPropertyFactory
    {
        private static Dictionary<string, ModelProperty> bpmap = new Dictionary<string, ModelProperty>();

        public static ModelProperty GetModelProperty(Type modelType)
        {
            if (bpmap.ContainsKey(modelType.FullName))
            {
                return bpmap[modelType.FullName];
            }
            ModelProperty bp = null;

            object t = GetAttribute(modelType, typeof(TableAttribute));
            if (t != null)
            {
                bp = new ModelProperty();
                bp.SetTableName(((TableAttribute)t).Name);

                PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Instance | BindingFlags.Public);
                foreach (PropertyInfo f in properties)
                {
                    object[] attrbs = f.GetCustomAttributes(typeof(ColumnAttribute), false);
                    if (attrbs.Length > 0)
                    {
                        ColumnAttribute colAttr = (ColumnAttribute)attrbs[0];
                        Column column = new Column(colAttr);
                        bp.AddColumn(column);

                        attrbs = f.GetCustomAttributes(typeof(PrimaryKeyAttribute), false);
                        if (attrbs.Length > 0)
                        {
                            PrimaryKeyAttribute primaryKeyAttribute = (PrimaryKeyAttribute)attrbs[0];
                            bp.SetPrimaryKey(primaryKeyAttribute);
                            bp.SetPkColumn(column);
                        }

                        attrbs = f.GetCustomAttributes(typeof(AutoGenerateAttribute), false);
                        if (attrbs.Length > 0)
                        {
                            column.AutoGenerateAttribute = (AutoGenerateAttribute)attrbs[0];
                        }
                    }
                }

            }

            return bp;
        }

        private static object GetAttribute(Type modelType, Type attributeType)
        {
            object[] attributes = modelType.GetCustomAttributes(attributeType, false);
            if (attributes.Length == 0) return null;

            return attributes[0];
        }

        
    }
}
